package com.h3c.ptability.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.eos.common.util.IdWorker;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3c.ptability.cache.UserCache;
import com.h3c.ptability.entity.PtAllWorker;
import com.h3c.ptability.entity.PtApp;
import com.h3c.ptability.entity.PtAppAdmin;
import com.h3c.ptability.mapper.PtAppAdminMapper;
import com.h3c.ptability.mapper.PtAppMapper;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IPtAppService;
import com.h3c.ptability.dto.PtAppDTO;
import com.h3c.ptability.utils.BusiEnumDefine;
import com.h3c.ptability.utils.InitExampleOrderByUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtAppServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_app serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtAppServiceImpl extends ServiceImpl<PtAppMapper, PtApp> implements IPtAppService {

    @Resource
    private PtAppMapper ptAppMapper;

    @Resource
    private PtAppAdminMapper ptappAdminMapper;

    @Autowired
    private CommService commService;

    /**
     * 模糊查询操作
     */
    @Override
    public List<PtAppDTO> selectFuzzyByDto(PtAppDTO dto) {
        Integer userRole = UserCache.getLoginUserRole();
        if (userRole == BusiEnumDefine.USER_ROLE_APP_ADMIN) {
            throw new BusinessException(StatusCodeEnum.UN_AUTH);
        }

        List<PtApp> list = ptAppMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtApp.class));
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        //管理员信息
        List<String> ids = list.stream().map(PtApp::getAppId).collect(Collectors.toList());
        QueryWrapper<PtAppAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(PtAppAdmin::getAppId, ids);
        List<PtAppAdmin> admins = ptappAdminMapper.selectList(queryWrapper);
        Map<String, List<PtAppAdmin>> appMap = admins.stream()
                .collect(Collectors.groupingBy(PtAppAdmin::getAppId, Collectors.toList()));
        List<PtAppDTO> ptAppDTOS = JSONArray.parseArray(JSONArray.toJSONString(list), PtAppDTO.class);
        for (PtAppDTO appDTO : ptAppDTOS) {
            List<PtAppAdmin> appAdmins = appMap.get(appDTO.getAppId());
            if (appAdmins != null) {
                String userIds = appAdmins.stream().map(PtAppAdmin::getUserId).collect(Collectors.joining(","));
                String userNames = appAdmins.stream().map(PtAppAdmin::getUserName).collect(Collectors.joining(","));
                appDTO.setUserIds(userIds);
                appDTO.setUserNames(userNames);
            }
        }
        return ptAppDTOS;
    }

    @Override
    public List<PtAppDTO> selectByDto(PtAppDTO dto) {
        //List<PtApp> list = ptAppMapper.selectByExample(initExample(dto));
        List<PtApp> list = ptAppMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto),PtApp.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtAppDTO.class);
    }

    /**
     * 插入操作
     */
    @Override
    @Transactional
    public Integer insertDto(PtAppDTO dto) {
        Integer userRole = UserCache.getLoginUserRole();
        if (userRole == BusiEnumDefine.USER_ROLE_APP_ADMIN) {
            throw new BusinessException(StatusCodeEnum.UN_AUTH);
        }

        PtApp ptApp = ptAppMapper.selectById(dto.getAppId());
        if (ptApp != null) {
            throw new BusinessException(StatusCodeEnum.ADD_FAIl.getCode(), "app已存在，请勿重复添加");
        }

        dto.setUpdateTime(new Date());
        dto.setUpdatorId(UserCache.getLoginUserNameAndId());
        dto.setCreateTime(new Date());
        dto.setCreatorId(UserCache.getLoginUserNameAndId());
        int i = ptAppMapper.insert(JSONObject.parseObject(JSON.toJSONString(dto), PtApp.class));
        insertAdmin(dto.getUserIds(), dto.getAppId());
        return i;
    }

    public void insertAdmin(String userIds, String appId) {
        if (StringUtils.isBlank(userIds)) {
            return;
        }
        String[] idArr = userIds.split(",");
        for (String id : idArr) {
            PtAllWorker worker = commService.getAllWorkerByWorkerId(id);
            if (worker == null) {
                log.error("查询不到员工数据：{}", id);
                continue;
            }
            String domainAccount = worker.getDomainAccount();
            String userName = worker.getWorkerName();
            PtAppAdmin ptAppAdmin = new PtAppAdmin();
            ptAppAdmin.setAppId(appId);
            ptAppAdmin.setAccount(domainAccount);
            ptAppAdmin.setUserId(id);
            ptAppAdmin.setUserName(userName);
            ptappAdminMapper.insert(ptAppAdmin);
            commService.deleteLoginUser(domainAccount);
        }
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    @Transactional
    public Integer updateDto(PtAppDTO dto) {
        String appId = dto.getAppId();

        deleteAdmin(appId);

        insertAdmin(dto.getUserIds(), appId);

        dto.setUpdateTime(new Date());
        dto.setUpdatorId(UserCache.getLoginUserNameAndId());
        return ptAppMapper.updateById(JSONObject.parseObject(JSON.toJSONString(dto), PtApp.class));
    }

    private void deleteAdmin(String appId) {
        Integer userRole = UserCache.getLoginUserRole();
        if (userRole == BusiEnumDefine.USER_ROLE_APP_ADMIN) {
            throw new BusinessException(StatusCodeEnum.UN_AUTH);
        }

        //清除缓存
        QueryWrapper<PtAppAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PtAppAdmin::getAppId, appId);
        List<PtAppAdmin> appAdmins = ptappAdminMapper.selectList(queryWrapper);
        appAdmins.stream().map(PtAppAdmin::getAccount).forEach(commService::deleteLoginUser);

        //删除
        ptappAdminMapper.delete(queryWrapper);
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    @Transactional
    public Integer deleteDto(PtAppDTO dto) {
        deleteAdmin(dto.getAppId());
        return ptAppMapper.deleteById(dto.getAppId());
    }
}
